package com.example.study.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.study.domain.ClasszDO;
import com.example.study.domain.StudentDO;
import com.example.study.domain.UserDO;
import com.example.study.service.IClasszService;
import com.example.study.service.IStudentService;
import com.example.study.service.IUserService;
import com.example.study.service.dto.StudentRespDTO;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequiredArgsConstructor
@RequestMapping("/student")
public class StudentController {

    private final IStudentService studentService;

    private final IUserService userService;

    private final IClasszService classzService;

    @GetMapping("/add")
    public String addStudentPage(HttpSession httpSession) {
        List<ClasszDO> list = classzService.list();
        httpSession.setAttribute("classzs",list);
        return "add_student";
    }

    @GetMapping("/deleteData")
    @ResponseBody
    public Map<String,Object> delete(Long id) {
        StudentDO byIdStudentDO = studentService.getById(id);
        if (BeanUtil.isEmpty(byIdStudentDO)) {
            return null;
        }
        userService.removeById(byIdStudentDO.getUserId());
        studentService.removeById(id);
        return null;
    }

    @GetMapping("/list")
    public String listStudentPage(HttpSession session) {
        List<StudentDO> list = studentService.list();
        List<StudentRespDTO> studentRespDTOS = BeanUtil.copyToList(list, StudentRespDTO.class);
        studentRespDTOS = studentRespDTOS.stream().map(item -> {
            ClasszDO byIdClasszDO = classzService.getById(item.getClassId());
            item.setClasszDO(byIdClasszDO);
            return item;
        }).collect(Collectors.toList());
        session.setAttribute("students",studentRespDTOS);
        return "student_list";
    }

    @PostMapping("/add")
    public String addStudent(StudentDO studentDO) {
        UserDO userDO = new UserDO();
        userDO.setUsername(studentDO.getStuNo());
        userDO.setPassword("123");
        userDO.setType("student");
        userService.save(userDO);

        studentDO.setUserId(userDO.getId());
        studentService.save(studentDO);
        return "redirect:/index";
    }
}
